import { downloadFile } from '@/utils';
import { Message } from 'element-ui';

export default (() => {
  let hasConnect = null;
  function exportWait(msg = '导出') {
    Message({
      dangerouslyUseHTMLString: true,
      message: `<i class="el-icon-loading" style="margin-right:6px;"></i><span style="color: #999;">正在${msg}，请等待</span>`,
      type: '',
      duration: 0
    });
  }
  function exportSuccess(msg = '导出') {
    Message.closeAll();
    Message({
      message: `${msg}成功！`,
      type: 'success',
      duration: 1500
    });
  }
  function exportFail(msg) {
    Message.closeAll();
    Message({
      message: msg || '请求失败！',
      type: 'error',
      duration: 1500
    });
  }
  /**
   * 表格导出-公共方法
   * @param {function} requestApi 接口
   * @param {string} fileName 文件名称
   * @param {object} queryForm 请求参数
   * @param {string} suffix 文件类型 默认xls
   */
  return ({
    requestApi,
    fileName,
    queryForm,
    suffix = '.xls'
  }, callBack) => {
    if (hasConnect) return;
    if (!requestApi) return;
    exportWait();
    hasConnect = true;
    requestApi(queryForm)
      .then(res => {
        const fileReader = new FileReader();
        fileReader.onload = function () {
          try {
            const jsonData = JSON.parse(this.result);
            exportFail(jsonData.exceptionContent);
          } catch (err) {
            if (window.navigator.msSaveBlob) {
              try {
                const blobObject = new Blob([res]);
                window.navigator.msSaveBlob(blobObject, `${fileName}${suffix}`);
                exportSuccess();
              } catch (e) {
                console.warn(e, 'ie11');
              }
              return;
            } else {
              downloadFile(res, fileName, suffix);
              exportSuccess();
            }
          }
        };
        fileReader.readAsText(res, 'utf-8');
      })
      .finally(() => {
        hasConnect = null;
        callBack && callBack();
      });
  };
})();
